﻿using Hopscotch.Common.Logging;
using Hopscotch.Presentation.Communication.Events;
using Hopscotch.Presentation.Communication.Util;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
using Microsoft.Practices.Prism.PubSubEvents;

namespace Hopscotch.Presentation.Communication
{
    public interface IEnqConnection
    {
        Hopscotch.Common.Contracts.EnqService.ConnectionState ConnectionState { get; }
    }

    public class EnqConnection : IEnqConnection
    {
        private readonly ILogger logger;
        private readonly IHubConnection hubConnection;
        private readonly IEventAggregator eventAggregator;

        public EnqConnection(HubConnection hubConnection, IEventAggregator eventAggregator)
        {
            logger = AppLogger.CreateLogger<EnqConnection>();

            this.hubConnection = hubConnection;
            this.eventAggregator = eventAggregator;

            hubConnection.StateChanged += hubConnection_StateChanged;
        }

        public Hopscotch.Common.Contracts.EnqService.ConnectionState ConnectionState
        {
            get 
            {
                return ConnectionStateMapper.Convert(this.hubConnection.State);
            }
        }

        private void hubConnection_StateChanged(StateChange obj)
        {
            var connectionEvent = new ConnectionChangedEvent()
            {
                ConnectionId = hubConnection.ConnectionId,
                ConnectionState = ConnectionStateMapper.Convert(hubConnection.State)
            };

            this.eventAggregator.GetEvent<ConnectionChangedEvent>().Publish(connectionEvent);

            logger.Info("hubConnection Id: {0} StateChanged New State: {1}", hubConnection.ConnectionId, hubConnection.State);
        }

    }
}
